package com.yao.nettydemo.wechat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Henry Yao
 * @date 2021/5/3
 */
public class WeChatServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 每个channel都有一个handler对象，设置成static保证共用一个，可能存在线程安全问题
     */
    private final static List<ChannelHandlerContext> clients = new ArrayList<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 将新的连接加入到集合中
        clients.add(ctx);
        String addr = ctx.channel().remoteAddress().toString();
        System.out.println(addr + "\t上线,当前在线人数为" + clients.size());
        for (ChannelHandlerContext context : clients) {
            if (context != ctx) {
                context.writeAndFlush(addr + "\t上线"+ "\r\n");
            }
        }
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 将连接从集合中移除
        clients.remove(ctx);
        String addr = ctx.channel().remoteAddress().toString();
        System.out.println(addr + "\t下线,当前在线人数为" + clients.size());
        for (ChannelHandlerContext context : clients) {
            if (context != ctx) {
                context.writeAndFlush(addr + "\t下线"+ "\r\n");
            }
        }
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 将消息转发到其他客户端
        System.out.println("收到" + ctx.channel().remoteAddress().toString() + "发来的消息：" + msg + ",现在开始转发。");
        for (ChannelHandlerContext context : clients) {
            if (context != ctx) {
                context.writeAndFlush(ctx.channel().remoteAddress().toString() + ":\t" + msg + "\r\n");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
